/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.httprequest.agent;

import org.utc.ia04.antsontheweb.httprequest.behaviour.HttpRequest;
import org.utc.ia04.antsontheweb.utilities.Requete;

import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;

public class HttpRequester extends Agent {

	//serialVersionUID
	private static final long serialVersionUID = -4154681408844059459L;
	public static final String DFTYPE = "HttpRequester";

	protected void setup()
	{
		/* --- DEBUG ---
		System.out.println("Requester cree !");
		//-------------*/	

		register();
		addBehaviour(new HttpRequest());
	}

	private void register()
	{
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType(HttpRequester.DFTYPE); 
		sd.setName(this.getName());
		dfd.addServices(sd);
		try { DFService.register(this, dfd); }
		catch (Exception fe) {}
	}
	
	public void takeDown()
	{
		/* --- DEBUG ---
		System.out.println("A requester dies !");
		//-------------*/
		
		ACLMessage m = new ACLMessage(ACLMessage.INFORM);
		Requete r = new Requete(Requete.REQUESTER_DIE, null);
		m.setContent(r.serialize());
		
		DFAgentDescription template = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(HttpReqPoolManager.DF_TYPE);
		template.addServices(sd);
		try
		{
			DFAgentDescription[] result = DFService.search(this, template);
			for(int i = 0; i < result.length; ++i)
				m.addReceiver(result[i].getName());
		}
		catch(Exception e) {}
		send(m);
		
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());

		try { DFService.deregister(this, dfd); }
		catch (FIPAException e) { }
	}
}
